/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step_fliter',
			title : 'Step过滤',
			type : 'LineEdit',
			property : {tool_tip : 'unit'},
		},
		{
			name : 'layer_type',
			title : '工作层',
			type : 'ComboBox',
			property : {
			    size_policy:'Expanding,Fixed',
			    item_list:[
			        {name:'outer',text:'outer'},
			        {name:'inner',text:'inner'},
			        {name:'all',text:'all'}
			    ],
			    tool_tip:'分析模式必须设置，未设定则退出'
			},
			pack : {row:1,column:1}
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.02 2020-04-28 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 线路补偿</p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> 配置 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("=====================>JTG_PUB_pos_edit_compensation_aim start");
/* question
    ?
*/
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}

if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var cfg = {
		plat_grapic: 2000
	}
	var par = PAR;
	var default_par = {  // par默认参数？
		step_fliter:"unit.+",
		step2:"unit",
		units: "mm",
		auto_save: "no"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	
	if(_.isEmpty(Job)){throw "参数Job不存在"}
    var job = Job.toLowerCase()
    // 料号验证
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
	if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }
	
	// 脚本开始
	var layer_config = {
		outer: {layer_type:"signal", side:"top|bottom", context:"board", polarity:"positive"},
		inner: {layer_type:"signal", side:"inner", context:"board", polarity:"positive"},
		all: {layer_type:"signal",side:"top|bottom|inner", context:"board", polarity:"positive"},
		power_ground: {layer_type:"power_ground", side:"inner", context:"board", polarity:"negative"},
	} 
	var layer_cfg
	if(par.layer_type != ""){
		layer_cfg = layer_config[par.layer_type]
	}
	
	var matrix = GEN.getMatrix({job:job})
	var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		var flag = true
		if(!layer_cfg){ return false}
		for(var k in layer_cfg){
			var tmp_reg = new RegExp(layer_cfg[k], "ig")
			if(!tmp_reg.test(val[k])){
				flag = false
			}
		}
		return flag
	})
	var out_layers = n_layers.filter(function(v){return /top|bottom/.test(matrix[v].side) })
	var signal_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		return val.layer_type == "signal" && val.context == "board"
	})
	if(n_layers.length == 0){throw "can not find layer"}
	var stepList = GEN.getStepList({job:job})
	if(par.step_fliter != ""){
		stepList = stepList.filter(function(v){
			var step_reg = new RegExp(par.step_fliter)
			return step_reg.test(v)})
	}
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job: job}).filter(function (v) {
			var step_reg = new RegExp(par.step2)
			return step_reg.test(v)
		})
	}
	// 获取料号info copper_base_thk_outer
	var layer_type = par.layer_type    // outer inner all power_ground
	var jtg_etch_process_mode = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_etch_process_mode"})
	var copper_etching_thk_outer = IKM.get_jobinfo({jobid:JobId, jobinfo:"copper_etching_thk_outer"})
	console.log("jtg_etch_process_mode:"+jtg_etch_process_mode);  // 蚀刻工艺 酸:mask_hole 碱:plat_grapic 无:non
	var ret = IKM.crud('selectArrayMap', {
        table: "pdm_job_stack_layers",
        field: ["layer_name","raw_thk"],
        where: {job_id:JobId}
	}).filter(function(item){return item.layer_name})
    var layerCount = IKM.get_jobinfo({jobid: JobId,jobinfo:"layer_count"}) || GEN.getLayerCount({job:job})
    var info = {};
    
    ret.map(function(row) {
        var layer = getRow(row.layer_name,layerCount) 
		var raw_thk = row.raw_thk
		info[layer] = raw_thk
	})
	// 阴阳铜
	var cores = IKM.crud('selectArrayMap', {
		table: "pdm_job_stack_layers",
		field: ["layer_num"],
		where: {job_id:JobId, layer_type:"Core"}
	})
	cores.forEach(function(num){
		var num1 = Math.floor(num)
		var num2 = Math.ceil(num)
		var layer1 = "l" +num1
		var layer2 = "l" +num2
		var raw1 = IKM.crud('selectValue', {
			table: "pdm_job_stack_layers",
			field: ["raw_thk"],
			where: {job_id:JobId, layer_num:num1}
		})
		var raw2 = IKM.crud('selectValue', {
			table: "pdm_job_stack_layers",
			field: ["raw_thk"],
			where: {job_id:JobId, layer_num:num2}
		})
		var raw;
		if(raw1 != raw2) {
			raw = Number(raw1) > Number(raw2) ? raw1 : raw2;
			info[getRow(layer1,layerCount)] = raw
			info[getRow(layer2,layerCount)] = raw
		}
	})
	stepList.forEach(function(step){
			GEN.openStep({job:job, name:step})
			GEN.units({type:par.units})
			GEN.clearLayers()
			GEN.affectedLayer({affected:'no',mode:'all'})
			if (layer_type == "all") {
				var innerlayers = n_layers.filter(function(layer){
					return out_layers.indexOf(layer) < 0
				})
				GEN.affectedLayer({affected:'no',mode:'all'})
				GEN.affectedLayer({affected:'yes',layer:innerlayers})
				resize_tmp({select:{feat_types:"line\;pad\;arc\;text",polarity:"positive"}, resize:resize.inner})
				GEN.affectedLayer({affected:'no',mode:'all'})
				GEN.affectedLayer({affected:'yes',layer:out_layers})
				resize_tmp({select:{feat_types:"line\;arc\;text",polarity:"positive"}, resize:resize.outer.line})
				resize_tmp({select:{feat_types:"pad",polarity:"positive"}, resize:resize.outer.pad})
			} else if(layer_type == "inner"){
                n_layers.forEach(function(layer) {
                    var raw_thk = info[layer]
                    if(raw_thk) {
                        GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
                        resize_tmp({select:{feat_types:"line\;pad\;arc\;text",polarity:"positive"}, resize:getBc({side:layer_type, paw:raw_thk})})
                    }
                })
			} else if(layer_type == "outer") {
                n_layers.forEach(function(layer) {
                    var raw_thk = copper_etching_thk_outer
                    var resize = getBc({side:layer_type, paw:raw_thk,jtg_etch_process_mode:jtg_etch_process_mode})
					GEN.workLayer({name:layer,display_number:2,clear_before:'yes'})
                    resize_tmp({select:{feat_types:"line\;arc\;text",polarity:"positive"}, resize:resize.line})
                    resize_tmp({select:{feat_types:"pad",polarity:"positive"}, resize:resize.pad})
                })
			}
			GEN.affectedLayer({affected:'no',mode:'all'})
			if(jtg_etch_process_mode == "plat_grapic" && out_layers.length>0){
				// 做参考层
				var tmp_layer = "drl_tmp";
				var tmp = {"25": 5,"32": 10,"42": 10,"60": 20,"75": 25,"90": 45}
				var raw = copper_etching_thk_outer;
				if(GEN.isLayerExists({job:job, layer:tmp_layer})){GEN.deleteLayer({job:job, layer:tmp_layer})}
				GEN.workLayer({name:'drl',display_number:2,clear_before:'yes'})
				GEN.selCopyOther({dest:'layer_name',target_layer:tmp_layer,invert:'no',dx:0,dy:0,size:cfg.plat_grapic})
				GEN.clearLayers()
				out_layers.forEach(function(layer){
					GEN.affectedLayer({affected:'yes',layer:layer,clear_before:"yes"})
					GEN.COM("filter_set,filter_name=popup,update_popup=no,feat_types=line\;arc")
					GEN.COM("sel_ref_feat,layers=drl_tmp,use=filter,mode=touch,pads_as=shape,f_types=line\;pad\;surface\;arc\;text,polarity=positive\;negative,include_syms=,exclude_syms=")
					GEN.COM('filter_reset',{filter_name : 'popup'});
					if (GEN.getSelectCount()>0) {
						if(tmp[raw]){
							GEN.COM('sel_resize',{size :tmp[raw] ,corner_ctl : 'no'});
						}
					}
				})
				GEN.deleteLayer({job:job, layer:tmp_layer})

				
			}
		})
	
	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}
    console.log("========================>JTG_PUB_pos_edit_compensation_aim end");
	if (mode === "aimdfm") {
		$.QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				progress: 33.33
			},
			where: { id: $.task_id }
		});
		if (GEN.hasError()) {
			Status = 'error';
			resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {
				status: Status,
				result_data: resultData
			};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {
				status: Status,
				result_data: resultData
			};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}


function resize_tmp(props){
	GEN.selectByFilter(props.select)
	if(GEN.getSelectCount()>0){
		GEN.selResize({size: props.resize})   // ? 
	}
}



function getRow( signal1, layerCount) {
    signal1 = Number(signal1.slice(1)) 
    if (signal1 == 1) {
        return "gtl"
    } else if (signal1 == layerCount) {
        return "gbl"
    } else {
        return "l" + signal1
    }
}

function getBc(props) {
    var side = props.side;
    var paw = props.paw;
    var jtg_etch_process_mode = props.jtg_etch_process_mode;
    if (side == "inner") {
        if(paw <= 18) {return 15} 
        else if (paw <=35) {return 30}
        else if (paw <=70) {return 60}
        else if (paw <=105) {return 110}
    } else if (side == "outer") {
        if (  jtg_etch_process_mode== "mask_hole") { //酸蚀
            if(paw <= 50 && paw >= 33) {return { line:35, pad: 40 }} 
            else if (paw <= 70 && paw >= 51) {return { line:55, pad: 60 }}
            else if (paw <= 85 && paw >= 71) {return { line:70, pad: 75 }}
            else if (paw <= 105 && paw >= 86) {return { line:95, pad: 100 }}
            else if (paw <= 130 && paw >= 106) {return { line:115, pad: 120 }}
        } else if(  jtg_etch_process_mode== "plat_grapic") {
            if(paw <= 25 ) {return { line:20, pad: 20 }} 
            else if (paw <= 32 ) {return { line:30, pad: 30 }}
            else if (paw <= 42 ) {return { line:40, pad: 40 }}
            else if (paw <= 60 ) {return { line:55, pad: 55 }}
            else if (paw <= 75 ) {return { line:65, pad: 65 }}
            else if (paw <= 95 ) {return { line:90, pad: 90 }}
        }
    }
    return 0
}